//项目亮点  可以像nuxt一样自动配置路由
//难点 扁平路由转换树形

//required.context('路径','是否递归引入'，'正则') 可以一次性导入多个模块

let files = require.context("@/pages", true, /\.vue$/);
// console.log(files.keys());

//创建路由配置
//{path:'',component:''}

let repeatRoutes = files.keys().map((path) => {
  //获取路径对应的每个.vue组件
  let currentComponent = files(path).default;
  //结构组件export default导出的对象中添加的属性
  let { meta, name, redirect } = currentComponent;
  // console.log(currentComponent.meta);

  //通过正则去掉index.vue或者去掉.vue的后缀
  let regExp = /(\/index\.vue|\.vue)$/;

  //substring 用来去掉一开始的第一个.
  path = path.substring(1).replace(regExp, "");
  // console.log(path);

  return {
    path: path ? path : "/pages",
    //重定向,name属性，meta路由元信息
    meta: meta ?? {},
    name: name ?? path.substring(1).split("/").join("-").toLowerCase(),
    redirect: redirect ?? null,
    component: () => import("@/pages" + path)
  };
});
// console.log(repeatRoutes);

function convertTree(repeatRoutes) {
  repeatRoutes = [...repeatRoutes]; //浅拷贝
  let treeRoutes = [];

  repeatRoutes.forEach((route) => {
    //去掉路径第一个斜杠，转换成数组
    let routePathArr = route.path.substring(1).split("/");
    // console.log(routePathArr);
    // length为1的都是根节点
    //添加id和pid

    //正常自己添加id
    route.id = routePathArr.join("-");

    if (routePathArr.length > 1) {
      //浅拷贝routePathArr
      let pathArr = [...routePathArr];
      pathArr.pop();
      let pid = pathArr.join("-");
      route.pid = pid; //添加父节点id
    }
  });
  //转换成树形数据
  repeatRoutes.forEach((route) => {
    //将所有路径变成小写   目的是和菜单的高亮效果绑定
    route.path = route.path.toLowerCase();
    if (route.path === "/page404") {
      route.path = "*";
    }
    //父亲在哪里
    let parent = repeatRoutes.find((v) => route.pid === v.id);
    if (parent) {
      if (!parent.children) {
        parent.children = [];
      }
      route.path = route.path.substring(1).split("/").pop();
      // console.log(route.path);
      parent.children.push(route);
    } else {
      treeRoutes.push(route);
    }
  });
  return treeRoutes;
}

let res = convertTree(repeatRoutes);
console.log(res);

export default [...res]; //做了个浅拷贝，为了别不小心把res改了
